<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * Description of OrderContronller
 *
 * @author Vu
 */
include APPLICATION_PATH."/models/Agent.php";
include APPLICATION_PATH."/models/Area.php";
include APPLICATION_PATH."/models/Product.php";
include APPLICATION_PATH ."/models/Agent_Product.php";
include APPLICATION_PATH."/models/Order.php";
include APPLICATION_PATH."/models/Order_Detail.php";
include APPLICATION_PATH."/models/Admin_Area.php";
    
class KinhDoanh_OrderController extends Zend_Controller_Action {
    //put your code here
    
    public function  init(){
        $bootstrap = $this->getInvokeArg("bootstrap");
        $this->aConfig = $bootstrap->getOptions();
        $this->view->aConfig = $this->aConfig;
        $this->Areamodel= new Model_Area();
        $this->AreamodelMapper = new Model_AreaMapper();
        $this->AgentProductmodel= new Model_Agent_Product();
        $this->AgentProductmodelMapper = new Model_Agent_ProductMapper();
        $this->Agentmodel= new Model_Agent();
        $this->AgentmodelMapper= new Model_AgentMapper();
        $this->model= new Model_Order();
        $this->modelMapper = new Model_OrderMapper();
        $this->OrderDeltailmodel=new Model_Order_Detail();
        $this->OrderDeltailmodelMapper= new Model_Order_DetailMapper();
        $this->AAmodelMapper = new Model_Admin_AreaMapper();        
        $this->kinhdoanh_id = GlobalLib::getLoginId();     
        $this->ProductmodelMapper = new Model_ProductMapper();
    }

    public function indexAction(){
        
    }            
    
    public function orderAction(){
        if($this->getRequest()->isPost()){
            $redirectUrl = $this->aConfig["site"]["url"] . "/kinhdoanh/order/index";
            $order_no = GlobalLib::createOrderNo();
            $user_id= GlobalLib::getUserLogin();
            $this->AgentmodelMapper->findbyid($user_id['id'],$this->Agentmodel);
            $agent_id=$this->Agentmodel->getId();
            $this->model->setStore_Id($agent_id);
            $this->model->setTotal_Price(0);
            $this->model->setTotal_Charges($_POST["charges"]);
            $this->model->setOrder_No($order_no);
            $this->model->setCreated(date("Y/m/d H:i:s"));
            $this->model->setCreated_By(1);
            $this->model->setOrder_Status_Id(1);
            $this->modelMapper->save($this->model);
            $this->OrderDeltailmodel->setOrder_Id($order_no);
            $this->OrderDeltailmodel->setProduct_Id($_POST["product_id"]);
            $this->OrderDeltailmodel->setQuantity($_POST["quantity"]);
            $this->OrderDeltailmodel->setAgent_Id($_POST["agent_id"]);
            $this->OrderDeltailmodel->setFactor($_POST["factor"]);
            $this->OrderDeltailmodel->setPrice(0);
            $this->OrderDeltailmodel->setCharges($_POST["charges"]);
            $this->OrderDeltailmodel->setOrder_Status_Id(1);
            $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
            $this->_redirect($redirectUrl);
        }
//        $area_id=0;
//        $agent_id=0;
//        $product_id=0;
        $this->view->storeHTML= GlobalLib::getComboByStore('store_id','agent' , 'id', 'name', 0,false,'form-control','','where agent.province_id in (select admin_area.area_id from admin_area where admin_area.admin_id ='.$this->kinhdoanh_id.')','','');
        $this->view->agentHTML= GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name',0,false,'form-control','','','','onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML= GlobalLib::getComboByProduct('product_id','product','id','name',0,false,'form-control','','','','onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#area_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        //        
        $this->view->popupareaHTML= GlobalLib::getComboByArea('popup_area_id', 'area', 'id', 'name', 0,false, 'form-control','', '','','onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#popup_area_id\').val(),\'popup_province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupprovinceHTML= GlobalLib::getComboByProvince('popup_province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= 0 )', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#popup_province_id\').val(),\'popup_district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupdistrictHTML=GlobalLib::getComboByDistrict('popup_district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id= 0');   
    }
//    public function serviceAction(){
//        $this->_helper->layout->disableLayout();
//        
//        
//        foreach ($this->modelMapper->fetchAll() as $items ) 
//        {   
//            $allnew = TRUE;
//            //Kiểm tra các chi tiết đều ở tình trạng hủy thì tình trạng đơn hàng là Hủy
//            $stt=0;
//            $sttCancell = 0;
//            foreach ($this->OrderDeltailmodelMapper->fetchAllByOrderNo($items->getOrder_No()) as $detailitem)
//            {
//                 if($items->getOrder_No()==$detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id()>1)
//                 {
//                     $allnew = FALSE;                     
//                 }
//                 $stt++;                
//                if($items->getOrder_No() == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() == 3){ $sttCancell++; }
//                
//            }           
//            if(!$allnew && $items->getOrder_Status_Id()=='1') $order_status_name = "Đang chờ duyệt";
//            else $order_status_name = GlobalLib::getName ("order_status", $items->getOrder_Status_Id(), "name");
//            if( $stt == $sttCancell){ $order_status_name ="Hủy"; }        
//            foreach ($this->OrderDeltailmodelMapper->fetchAllByOrderNo($items->getOrder_No()) as $detailitem)
//            {
//                if($items->getOrder_No()==$detailitem->getOrder_Id())
//                {
//                    $this->AgentmodelMapper->find($items->getStore_Id(),$this->Agentmodel);   
//                    foreach($this->AAmodelMapper->fetchAll() as $filter)
//                    if($this->Agentmodel->getProvince_Id()==$filter->getArea_Id() 
//                            && $filter->getAdmin_Id()==$this->kinhdoanh_id)
//                    {
//                        $menber[]=array(
//                            'id'=>$items->getId(),
//                            'store_name'=>  GlobalLib::getName('agent', $items->getStore_Id(),'name'),                                  
//                            'order_no'=> $items->getOrder_No(),
//                            'total_charges'=>$items->getTotal_Charges(),
//                            'created'=> ($items->getCreated()),
//                            'order_status'=>  $order_status_name
//                        );
//                        break;
//                    }
//                }
//            }
//        }
//        //echo json_encode($menber);
//        $json_array = $menber;
//
//        $new_array = array();
//        $exists    = array();
//        foreach( $json_array as $element ) {
//            if( !in_array( $element['order_no'], $exists )) {
//                $new_array[] = $element;
//                $exists[]    = $element['order_no'];
//            }
//        }
//        //Zend_Debug::dump($new_array);
//        echo json_encode($new_array);
//        
//        exit();
//    }
    public function serviceAction() {
        $this->_helper->layout->disableLayout();
        foreach ($this->modelMapper->fetchAllByKinhDoanh_Id($this->kinhdoanh_id) as $items) {
            $allnew = TRUE;
            //Kiểm tra các chi tiết đều ở tình trạng hủy thì tình trạng đơn hàng là Hủy
            $stt = 0;
            $sttCancell = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAllByOrderNo($items['order_no']) as $detailitem) {
                if ($items['order_no'] == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() > 1) {
                    $allnew = FALSE;
                }
                $stt++;
                if ($items['order_no'] == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() == 3) {
                    $sttCancell++;
                }
            }
            if (!$allnew && $items['order_status'] == '1')
                $order_status_name = "Đang chờ duyệt";
            else
                $order_status_name = GlobalLib::getName("order_status", $items['order_status'], "name");
            if ($stt == $sttCancell) {
                $order_status_name = "Hủy";
            }      
            $menber[] = array(
                'id' => $items['order_id'],
                'store_name' => $items['agent_name'],
                'order_no' => $items['order_no'],
                'total_charges' => $items['total_charges'],
                'created' => ($items['created']),
                'order_status' => $order_status_name
            );
        }
        echo json_encode($menber);
        exit();
    }
    public function servicedetailAction(){
        $this->_helper->layout->disableLayout();
        $order_id=$this->getParam("order_id","0");        
        foreach ($this->OrderDeltailmodelMapper->fetchAllByOrderNo($order_id) as $items ) 
        {                            
            $this->AgentmodelMapper->find($items->getAgent_Id(),$this->Agentmodel);
            $order_status = GlobalLib::getName("order_status", $items->getOrder_Status_Id() ,"name");            
                if($items->getModified_By()==0){
                    $modified_by = "";
                }else{
                    $firt_name = GlobalLib::getName ("admin",$items->getModified_By() ,'first_name');
                    $last_name = GlobalLib::getName ("admin",$items->getModified_By() ,'last_name');
                    $modified_by=$firt_name.' '.$last_name;
                }
                $product_name = "Sản phẩm đã bị xoá!";                                        
                if($this->ProductmodelMapper->findIn($items->getProduct_Id())!=null)
                    $product_name = GlobalLib::getName('product', $items->getProduct_Id(),'name');                   
                $menber[]=array(
                    'id'=>$items->getId(),
                    'product_name'=> $product_name,                                  
                    'quantity'=> $items->getQuantity(),
                    'price'=>$items->getPrice(),
                    'order_created'=>  GlobalLib::viewDate($items->getOrder_Created()),
                    'factor'=>  $items->getFactor(),
                    'charges'=>  $items->getCharges(),
                    'modified'=> GlobalLib::viewDate($items->getModified()),
                    'modified_by' => $modified_by,
                    'agent_name'=> GlobalLib::getName("agent", $items->getAgent_Id(), "name"),
                    'order_status_name' => $order_status,
                    'order_status_id' => $items->getOrder_Status_Id(),
                    'in' => TRUE
                );
        }        
        echo json_encode($menber);
        exit();
    }
    public  function detailAction()
    {
        $id = $this->_getParam("id","0");
        $this->modelMapper->findbyid($id,$this->model);
        $redirectUrl=$this->aConfig["site"]["url"]."kinhdoanh/order/index";
        $getId=$this->model->getId();
        if(empty($getId)){
             $this->_redirect($redirectUrl);
        }
        $allnew = TRUE;
        $count = 1;
        foreach ($this->OrderDeltailmodelMapper->fetchAll() as $detailitem)
        {
             $this->AgentmodelMapper->find($detailitem->getAgent_Id(),$this->Agentmodel);
             if($this->model->getOrder_No()==$detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id()>1)
             {
                 $allnew = FALSE;                 
             }
             foreach($this->AAmodelMapper->fetchAll() as $filter)
             if($this->model->getOrder_No()==$detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() ==1
                    && $this->Agentmodel->getProvince_Id() == $filter->getArea_Id() 
                     && $filter->getAdmin_Id() == $this->kinhdoanh_id) $count++;
        }        
        if(!$allnew && $this->model->getOrder_Status_Id()=='1') $order_status_name = "Đang chờ duyệt";
        else $order_status_name = GlobalLib::getName ("order_status", $this->model->getOrder_Status_Id(), "name");
        $this->view->order_status_name = $order_status_name;
        $this->view->count =$count;
        $this->view->item = $this->model;        
    }        
    public function addorderdetailAction()
    {               
        $id= $this->_getParam("id","0");        
        if($this->getRequest()->isPost()){                
            $check_exist = FALSE;
            foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
            {                                
                if($items->getOrder_Id()==$_POST['order_no'])
                {                        
                    if($items->getProduct_Id()==$_POST['product_id'] &&
                            $items->getAgent_Id()==$_POST['agent_id'] &&
                            GlobalLib::viewDate($items->getOrder_Created())==$_POST['order_created'])
                    {
                        $check_exist=TRUE;
                        $items->setQuantity($items->getQuantity()+intval($_POST['quantity']));
                        $items->setCharges($items->getCharges()+intval($_POST['charges']));
                        $items->setOrder_Status_Id(intval($_POST['submit_type']));
                        if(intval($_POST['submit_type'])==2) 
                        {
                            $items->setModified(date("Y/m/d H:i:s"));
                            $items->setModified_By(GlobalLib::getLoginId());
                        }
                        $this->OrderDeltailmodelMapper->save($items);
                    }                    
                }
            }
            $this->modelMapper->find($id,$this->model);
            if(!$check_exist)
            {
                $this->OrderDeltailmodel = new Model_Order_Detail();
                $this->OrderDeltailmodel->setOrder_Id($_POST['order_no']);
                $this->OrderDeltailmodel->setProduct_Id($_POST['product_id']);
                $this->OrderDeltailmodel->setQuantity($_POST['quantity']);
                $this->OrderDeltailmodel->setFactor($_POST['factor']);
                $this->OrderDeltailmodel->setCharges($_POST['charges']);
                $this->OrderDeltailmodel->setAgent_Id($_POST['agent_id']);                
                $this->OrderDeltailmodel->setOrder_Status_Id(intval($_POST['submit_type']));
                if(intval($_POST['submit_type'])==2) 
                        {
                            $items->setModified(date("Y/m/d H:i:s"));
                            $items->setModified_By(GlobalLib::getLoginId());
                        }
                $this->OrderDeltailmodel->setOrder_Created(GlobalLib::toMysqlDateString($_POST['order_created']));
                $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
            }
             // tich diem cho order
            $sum_order_charges =0;
            foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
            {            
                if($items->getOrder_Id()==$this->model->getOrder_No() && $items->getOrder_Status_Id()==2)
                {
                    $sum_order_charges += $items->getCharges();
                    $Order_detail=$items;
                }    
            }
            $this->model->setTotal_Charges($sum_order_charges);  
            $this->modelMapper->save($this->model);
             // update diem cho store
            $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);               
            $sum_store_charges = 0;
            foreach ($this->modelMapper->fetchAll() as $items)
            {                   
                if($items->getStore_Id()==$this->Agentmodel->getId())
                    $sum_store_charges+= $items->getTotal_Charges();
            }       
            $this->Agentmodel->setCharges($sum_store_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);        
            // update diem cho agent        
            $this->AgentmodelMapper->find(intval($_POST['agent_id']),$this->Agentmodel);                
            $sum_agent_charges = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items)
            {                   
                if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                    $sum_agent_charges+= $items->getCharges();
            }
            $this->Agentmodel->setCharges_Sell($sum_agent_charges);        
            $this->AgentmodelMapper->save($this->Agentmodel);   
            //redirect
            $this->_redirect('/kinhdoanh/order/addorderdetail/id/'.$id);
        }        
        $this->modelMapper->find($id,$this->model);
        $this->view->item = $this->model;                  
        $this->view->agentHTML= GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name',0,false,'form-control','','','','onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML= GlobalLib::getComboByProduct('product_id','product','id','name',0,false,'form-control','','','','onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#area_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        
        $this->view->popupareaHTML= GlobalLib::getComboByArea('popup_area_id', 'area', 'id', 'name', 0,false, 'form-control','', '','','onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#popup_area_id\').val(),\'popup_province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupprovinceHTML= GlobalLib::getComboByProvince('popup_province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= 0 )', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#popup_province_id\').val(),\'popup_district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupdistrictHTML=GlobalLib::getComboByDistrict('popup_district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id= 0');   
    }
    public function editorderdetailAction()
    {
        $id = $this->_getParam("id","0");
        $this->OrderDeltailmodelMapper->find($id,$this->OrderDeltailmodel);
        foreach($this->modelMapper->fetchAll() as $items)
        {
            if($this->OrderDeltailmodel->getOrder_Id()==$items->getOrder_No())
                $this->model = $items;
        }   
        if($this->getRequest()->isPost()){         
            $this->OrderDeltailmodelMapper->find($id,$this->OrderDeltailmodel)  ;          
            $this->OrderDeltailmodel->setProduct_Id($_POST['product_id']);
            $this->OrderDeltailmodel->setQuantity($_POST['quantity']);
            $this->OrderDeltailmodel->setFactor($_POST['factor']);
            $this->OrderDeltailmodel->setCharges($_POST['charges']);
            $this->OrderDeltailmodel->setAgent_Id($_POST['agent_id']);                
            $this->OrderDeltailmodel->setOrder_Status_Id(intval($_POST['submit_type']));
            if(intval($_POST['submit_type'])==2) 
                        {
                            $this->OrderDeltailmodel->setModified(date("Y/m/d H:i:s"));
                            $this->OrderDeltailmodel->setModified_By(GlobalLib::getLoginId());
                        }
            $this->OrderDeltailmodel->setOrder_Created(GlobalLib::toMysqlDateString($_POST['order_created']));
            $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
             // tich diem cho order
            $sum_order_charges =0;
            foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
            {            
                if($items->getOrder_Id()==$this->model->getOrder_No() && $items->getOrder_Status_Id()==2)
                {
                    $sum_order_charges += $items->getCharges();
                    $Order_detail=$items;
                }    
            }
            $this->model->setTotal_Charges($sum_order_charges);  
            $this->modelMapper->save($this->model);
             // update diem cho store
            $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);               
            $sum_store_charges = 0;
            foreach ($this->modelMapper->fetchAll() as $items)
            {                   
                if($items->getStore_Id()==$this->Agentmodel->getId())
                    $sum_store_charges+= $items->getTotal_Charges();
            }       
            $this->Agentmodel->setCharges_Sell($sum_store_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);        
            // update diem cho agent        
            $this->AgentmodelMapper->find(intval($_POST['agent_id']),$this->Agentmodel);                
            $sum_agent_charges = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items)
            {                   
                if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                    $sum_agent_charges+= $items->getCharges();
            }
            $this->Agentmodel->setCharges($sum_agent_charges);        
            $this->AgentmodelMapper->save($this->Agentmodel); 
            //redirect
            $this->_redirect('/kinhdoanh/order/detail/id/'.$this->model->id);
        }             
        $this->view->item = $this->model;          
        $this->view->item_detail = $this->OrderDeltailmodel;
        $this->view->agentHTML= GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name',$this->OrderDeltailmodel->getAgent_Id(),false,'form-control','','','','onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML= GlobalLib::getComboByProduct('product_id','product','id','name',$this->OrderDeltailmodel->getProduct_Id(),false,'form-control','','','','onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#area_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        //
        $this->view->popupareaHTML= GlobalLib::getComboByArea('popup_area_id', 'area', 'id', 'name', 0,false, 'form-control','', '','','onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#popup_area_id\').val(),\'popup_province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupprovinceHTML= GlobalLib::getComboByProvince('popup_province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= 0 )', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#popup_province_id\').val(),\'popup_district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupdistrictHTML=GlobalLib::getComboByDistrict('popup_district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id= 0');   
    }

    public function orderbrowserAction()
    {
        $id = $this->_getParam("id","0");
        // layorder
        $this->modelMapper->find($id,$this->model);
        // thay doi order_status_id cho tat ca order_detail = 1 thuoc khu vuc
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {
            $this->AgentmodelMapper->find($items->getAgent_Id(),$this->Agentmodel);     
            
                $items->setOrder_Status_Id(2);
                
                $items->setModified(date("Y/m/d H:i:s"));
                $items->setModified_By(GlobalLib::getLoginId());
                
                $this->OrderDeltailmodelMapper->save($items);                
        }
        // kiem tra order_detail -> thay doi trang thai order
        $checkorder =TRUE;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {
            if($items->getOrder_Id()==$this->model->getOrder_No() && $items->getOrder_Status_Id()==1)
            {    
                $checkorder = FALSE;
            }
        }
        if($checkorder) 
        {
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
        }
        // tich diem cho order
        $sum_order_charges =0;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {            
            if($items->getOrder_Id()==$this->model->getOrder_No() && $items->getOrder_Status_Id()==2)
            {
                $sum_order_charges += $items->getCharges();
                $Order_detail=$items;
            }    
        }        
        $this->model->setTotal_Charges($sum_order_charges);  
        $this->modelMapper->save($this->model);        
        // update diem cho store
        $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);               
        $sum_store_charges = 0;
        foreach ($this->modelMapper->fetchAll() as $items)
        {                   
            if($items->getStore_Id()==$this->Agentmodel->getId())
                $sum_store_charges+= $items->getTotal_Charges();
        }       
        $this->Agentmodel->setCharges($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);        
        // update diem cho agent      
                
        $this->AgentmodelMapper->find($Order_detail->getAgent_Id(),$this->Agentmodel);                
        $sum_agent_charges = 0;
        foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {                   
            if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                $sum_agent_charges+= $items->getCharges();
        }           
        $this->Agentmodel->setCharges_Sell($sum_agent_charges);        
        $this->AgentmodelMapper->save($this->Agentmodel); 
        
        //redirect
       $this->_redirect($this->aConfig["site"]["url"].'kinhdoanh/order/index');
    }
    public function ordercancelAction()
    {
        $id = $this->_getParam("id","0");
        // lay order
        $this->modelMapper->find($id,$this->model);        
        // thay doi order_status_id cho tat ca order_detail = 1 thuoc khu vuc
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {
            $this->AgentmodelMapper->find($items->getAgent_Id(),$this->Agentmodel);  

                $items->setOrder_Status_Id(3);
                $items->setModified(date("Y/m/d H:i:s"));
                $items->setModified_By(GlobalLib::getLoginId());
                $this->OrderDeltailmodelMapper->save($items);                
        }
        // kiem tra order_detail -> thay doi trang thai order
        $checkorder =TRUE;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {
            if($items->getOrder_Id()==$this->model->getOrder_No() && $items->getOrder_Status_Id()==1)
            {    
                $checkorder = FALSE;
            }
        }
        if($checkorder) 
        {
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
        }
        //redirect
       $this->_redirect($this->aConfig["site"]["url"].'kinhdoanh/order/index');
    }
    public function browserAction() {
        $id = $this->_getParam("id","0");
        // get order_detail
        $this->OrderDeltailmodelMapper->find($id,$this->OrderDeltailmodel);
        // thay doi trang thai order_detail
        $this->OrderDeltailmodel->setOrder_Status_Id(2);
        $this->OrderDeltailmodel->setModified(date("Y/m/d H:i:s"));
        $this->OrderDeltailmodel->setModified_By(GlobalLib::getLoginId());
        $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);        
        // lay order_id
        $order_id = $this->OrderDeltailmodel->getOrder_Id();
        // get order
        foreach ($this->modelMapper->fetchAll() as $items)
        {
            if($items->getOrder_No()==$order_id)  
            {
                $this->model = $items;
            }                        
        }
        // tich diem cho order
        $sum_order_charges =0;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {            
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==2)
            {
                $sum_order_charges += $items->getCharges();
            }    
        }
        $this->model->setTotal_Charges($sum_order_charges);  
        $this->modelMapper->save($this->model);
        // kiem tra order_detail -> thay doi trang thai order
        $checkorder =TRUE;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==1)
            {    
                $checkorder = FALSE;
            }            
        }
        if($checkorder) 
        {
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
        }
        // update diem cho store
        $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);        
        $sum_store_charges = 0;
        foreach ($this->modelMapper->fetchAll() as $items)
        {                   
            if($items->getStore_Id()==$this->Agentmodel->getId())
                $sum_store_charges+= $items->getTotal_Charges();
        }
        $this->Agentmodel->setCharges($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // update diem cho agent
        $this->AgentmodelMapper->find($this->OrderDeltailmodel->getAgent_Id(),$this->Agentmodel);        
        $sum_agent_charges = 0;
        foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {                   
            if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                $sum_agent_charges+= $items->getCharges();
        }                
        $this->Agentmodel->setCharges_Sell($sum_agent_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // redirect
        $this->_redirect($this->aConfig["site"]["url"].'kinhdoanh/order/detail/id/'.$this->model->getOrder_No());
    }
    public function cancelAction() {
        $id = $this->_getParam("id","0");
        // get order_detail
        $this->OrderDeltailmodelMapper->find($id,$this->OrderDeltailmodel);
        // thay doi trang thai order_detail
        $this->OrderDeltailmodel->setOrder_Status_Id(3);
        $this->OrderDeltailmodel->setModified(date("Y/m/d H:i:s"));
        $this->OrderDeltailmodel->setModified_By(GlobalLib::getLoginId());
        $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);        
        // lay order_id
        $order_id = $this->OrderDeltailmodel->getOrder_Id();
        // get order
        foreach ($this->modelMapper->fetchAll() as $items)
        {
            if($items->getOrder_No()==$order_id)  
            {
                $this->model = $items;
            }                        
        }
        // tich diem cho order
        $sum_order_charges =0;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {            
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==2)
            {
                $sum_order_charges += $items->getCharges();
            }    
        }
        $this->model->setTotal_Charges($sum_order_charges);  
        $this->modelMapper->save($this->model);
        // kiem tra order_detail -> thay doi trang thai order
        $checkorder =TRUE;
        foreach($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==1)
            {    
                $checkorder = FALSE;
            }
        }
        if($checkorder) 
        {
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
        }
        // update diem cho store
        $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);        
        $sum_store_charges = 0;
        foreach ($this->modelMapper->fetchAll() as $items)
        {                   
            if($items->getStore_Id()==$this->Agentmodel->getId())
                $sum_store_charges+= $items->getTotal_Charges();
        }
        $this->Agentmodel->setCharges($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // update diem cho agent
        $this->AgentmodelMapper->find($this->OrderDeltailmodel->getAgent_Id(),$this->Agentmodel);        
        $sum_store_charges = 0;
        foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items)
        {                   
            if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                $sum_store_charges+= $items->getCharges();
        }
        $this->Agentmodel->setCharges_Sell($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // redirect
        $this->_redirect($this->aConfig["site"]["url"].'kinhdoanh/order/detail/id/'.$this->model->getOrder_No());    
    }
    public function addorderAction() {     
            $redirectUrl = $this->aConfig["site"]["url"] . "/default/order/index";            
            $order_no = GlobalLib::createOrderNo();
            $agent_id = $this->_getParam("store_id","");
            $total_charges=$this->_getParam("total_charges","");
            $this->model->setStore_Id($agent_id);
            $this->model->setTotal_Price(0);
            $this->model->setTotal_Charges($total_charges);
            $this->model->setOrder_No($order_no);
            $this->model->setCreated(date("Y/m/d H:i:s"));
            $this->model->setCreated_By(1);
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
            $this->AgentmodelMapper->find($agent_id,$this->Agentmodel);
            $sum_store_charges=  $this->Agentmodel->getCharges()+$total_charges;
            $this->Agentmodel->setCharges($sum_store_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);
            echo $order_no;
            exit();
    }
    public function adddetailAction() {                
        $order_no = $this->getParam("order_no","0");
        if($order_no=="0")
        {
            $this->_redirect($this->aConfig["site"]["url"] . "/default/order/index");
        }
        $product_id = $this->_getParam("product_id","0");
        $quantity = $this->_getParam("quantity","0");
        $agent_id = $this->_getParam("agent_id","0");
        $factor = $this->_getParam("factor","0");
        $charges = $this->_getParam("charges","0");
        $order_created = $this->_getParam("order_created","0");
        $this->OrderDeltailmodel->setOrder_Created(GlobalLib::toMysqlDateString($order_created));
        $this->OrderDeltailmodel->setOrder_Id($order_no);
        $this->OrderDeltailmodel->setProduct_Id($product_id);
        $this->OrderDeltailmodel->setQuantity($quantity);
        $this->OrderDeltailmodel->setAgent_Id($agent_id);
        $this->OrderDeltailmodel->setFactor($factor);
        $this->OrderDeltailmodel->setPrice(0);
        $this->OrderDeltailmodel->setCharges($charges);
        $this->OrderDeltailmodel->setOrder_Status_Id(2);
        $this->OrderDeltailmodel->setModified(date("Y/m/d H:i:s"));
        $this->OrderDeltailmodel->setModified_By(GlobalLib::getLoginId());
        $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
        echo $order_no;
        exit();
    }
    public function addagentAction() {
        if($this->getRequest()->isPost())
        {
            $name = $this->_getParam("name","");
            $address = $this->_getParam("address","");
            $area_id = $this->_getParam("area_id","0");
            $province_id = $this->_getParam("province_id","0");
            $district_id = $this->_getParam("district_id","0");
            $representavie = $this->_getParam("representavie","");
            $phone = $this->_getParam("phone","");
            $agent_cat_id = $this->_getParam("agent_cat_id","0");
            $agent_status =1;
            $this->Agentmodel->setCharges(0);
            $this->Agentmodel->setCharges_Sell(0);
            $this->Agentmodel->setName($name);
            $this->Agentmodel->setAddress($address);
            $this->Agentmodel->setArea_Id($area_id);
            $this->Agentmodel->setProvince_Id($province_id);
            $this->Agentmodel->setDistrict_Id($district_id);
            $this->Agentmodel->setRepresentavie($representavie);
            $this->Agentmodel->setPhone($phone);
            $this->Agentmodel->setAgent_Cat_Id($agent_cat_id);
            $this->Agentmodel->setStatus($agent_status); 
            $this->Agentmodel->setAgent_Status(1);
            $this->AgentmodelMapper->save($this->Agentmodel);
            echo $this->AgentmodelMapper->getlastid();        
            exit();
        }
    }
}
